{% extends "base.html" %}
{% block title %}中间件管理 - IT资产管理平台{% endblock %}

{% block content %}
<!-- 顶部操作区域：搜索、添加、批量删除、选择列 -->
<div class="content-header" style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
  <!-- 左侧标题区域 -->
  <div class="header-title" style="flex: 0 0 auto;">
    <h2 style="margin: 0;">中间件列表</h2>
  </div>
  <!-- 右侧操作区域 -->
  <div class="header-actions" style="flex: 0 0 auto; display: flex; align-items: center;">
    <form id="searchForm" method="get" action="{{ url_for('middlewares') }}"
          style="display: flex; align-items: center; margin-right: 10px;">
      <input type="text" name="q" placeholder="搜索中间件..." value="{{ q|default('') }}"
             style="padding: 6px; border: 1px solid #bdc3c7; border-radius: 4px;">
      <button type="submit" class="btn btn-primary" style="margin-left: 5px;">搜索</button>
      <input type="hidden" name="per_page" value="{{ per_page }}">
    </form>
    <button id="addMiddlewareBtn" class="btn btn-primary" style="margin-right: 10px;">添加</button>
    <button id="batchDeleteBtn" class="btn btn-danger" style="margin-right: 10px;">批量删除</button>
    <button id="chooseColsBtn" class="btn btn-secondary">选择列</button>
  </div>
</div>


<!-- 中间件列表表格 -->
<div class="table-wrapper">
  <table class="property-table">
    <thead>
      <tr>
        <th><input type="checkbox" id="selectAll"></th>
        {% for prop in middleware_properties|default([]) %}
          <th class="col-{{ prop.name|replace(' ', '_') }}">{{ prop.name }}</th>
        {% endfor %}
        <th class="fixed-col">操作</th>
      </tr>
    </thead>
    <tbody>
      {% for middleware in middlewares|default([]) %}
      <tr data-id="{{ middleware.id }}" data-record='{{ middleware|tojson|safe }}'>
        <td><input type="checkbox" name="selected_ids" class="selectItem" value="{{ middleware.id }}"></td>
        {% for prop in middleware_properties|default([]) %}
          {% if prop.type == 'password' %}
            <td class="col-{{ prop.name|replace(' ', '_') }}">
              <span class="password-hidden">******</span>
              <span class="password-real" style="display: none;">{{ middleware[prop.name]|default('') }}</span>
              <i class="toggle-password fa fa-eye" style="cursor: pointer; margin-left: 5px;"></i>
            </td>
          {% else %}
            <td class="col-{{ prop.name|replace(' ', '_') }}">{{ middleware[prop.name]|default('') }}</td>
          {% endif %}
        {% endfor %}
        <td class="fixed-col">
          <button class="editBtn btn btn-sm btn-primary" data-id="{{ middleware.id }}" style="margin-right: 5px;">修改</button>
          <button class="deleteBtn btn btn-sm btn-danger" data-id="{{ middleware.id }}">删除</button>
        </td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>

<!-- 分页导航区域 -->
{% if total_pages is defined %}
<div class="pagination" style="margin-top: 20px; display: flex; justify-content: center; align-items: center;">
  <div style="margin-right: 20px;">
    每页：
    <select id="perPageSelect" onchange="onPerPageChange(this.value)">
      <option value="5" {% if per_page == 5 %}selected{% endif %}>5</option>
      <option value="10" {% if per_page == 10 %}selected{% endif %}>10</option>
      <option value="20" {% if per_page == 20 %}selected{% endif %}>20</option>
      <option value="50" {% if per_page == 50 %}selected{% endif %}>50</option>
    </select>
  </div>
  <div style="margin-right: 20px;">
    第 {{ page }} 页 / 共 {{ total_pages }} 页 (总记录数: {{ total }})
  </div>
  <div>
    {% if page > 1 %}
      <a href="{{ url_for('middlewares', page=page-1, per_page=per_page, q=q) }}" style="margin-right: 10px;">上一页</a>
    {% endif %}
    {% if page < total_pages %}
      <a href="{{ url_for('middlewares', page=page+1, per_page=per_page, q=q) }}" style="margin-left: 10px;">下一页</a>
    {% endif %}
  </div>
</div>
{% endif %}

<!-- 添加中间件弹窗 -->
<div id="addMiddlewareModal" class="modal">
  <div class="modal-content">
    <span class="close" id="addMiddlewareClose">&times;</span>
    <h3>添加中间件</h3>
    <form id="addMiddlewareForm" method="post" action="{{ url_for('add_middleware') }}">
      {% for prop in middleware_properties|default([]) %}
      <div class="form-group">
        <label for="middleware_field_{{ loop.index }}">{{ prop.name }}{% if prop.required %}*{% endif %}</label>
        <input type="text" name="{{ prop.name }}" id="middleware_field_{{ loop.index }}" placeholder="{{ prop.placeholder|default('') }}">
      </div>
      {% endfor %}
      <div class="form-group buttons">
        <button type="submit" class="btn btn-success">确认</button>
        <button type="button" id="middlewareCancelBtn" class="btn btn-secondary">取消</button>
      </div>
    </form>
  </div>
</div>

<!-- 编辑中间件弹窗 -->
<div id="editMiddlewareModal" class="modal">
  <div class="modal-content">
    <span class="close" id="editMiddlewareClose">&times;</span>
    <h3>修改中间件</h3>
    <form id="editMiddlewareForm" method="post">
      {% for prop in middleware_properties|default([]) %}
      <div class="form-group">
        <label for="edit_middleware_field_{{ loop.index }}">{{ prop.name }}{% if prop.required %}*{% endif %}</label>
        <input type="text" name="{{ prop.name }}" id="edit_middleware_field_{{ loop.index }}" placeholder="{{ prop.placeholder|default('') }}">
      </div>
      {% endfor %}
      <div class="form-group buttons">
        <button type="submit" class="btn btn-success">确认</button>
        <button type="button" id="editMiddlewareCancelBtn" class="btn btn-secondary">取消</button>
      </div>
    </form>
  </div>
</div>

<!-- 可选列弹窗 -->
<div id="columnModal" class="modal">
  <div class="modal-content column-modal-content">
    <span class="close" id="columnClose">&times;</span>
    <h3>选择显示的列</h3>
    <form id="columnForm">
      <div class="column-options-container">
        {% for prop in middleware_properties|default([]) %}
        <div class="column-option">
          <label>
            <input type="checkbox" name="columns" value="{{ prop.name|replace(' ', '_') }}" checked>
            <span class="column-label">{{ prop.name }}</span>
          </label>
        </div>
        {% endfor %}
      </div>
      <div class="form-group buttons">
        <button type="submit" class="btn btn-primary">确认</button>
        <button type="button" id="columnCancelBtn" class="btn btn-secondary">取消</button>
      </div>
    </form>
  </div>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
document.addEventListener("DOMContentLoaded", function(){

  // 将后端传入的 middleware_properties 转换为前端对象（用于字段验证）
  var propertiesData = {{ middleware_properties|default([])|tojson|safe }};
  var selectAllCheckbox = document.getElementById("selectAll");
  if (selectAllCheckbox) {
    selectAllCheckbox.addEventListener("click", function() {
      // 获取所有复选框（使用 querySelectorAll 返回 NodeList）
      var items = document.querySelectorAll(".selectItem");
      // 如果 NodeList 不支持 forEach，可以先转换为数组：
      Array.prototype.forEach.call(items, function(item) {
        item.checked = selectAllCheckbox.checked;
      });
    });
  }

  // 分页下拉选择处理函数
  function onPerPageChange(perPage) {
    var currentUrl = new URL(window.location.href);
    currentUrl.searchParams.set("per_page", perPage);
    currentUrl.searchParams.set("page", 1);
    window.location.href = currentUrl.toString();
  }

  // 辅助函数：清除错误提示
  function clearErrors(form) {
    form.querySelectorAll('.error-message').forEach(function(err) {
      err.remove();
    });
  }
  // 辅助函数：显示错误提示
  function showError(field, message) {
    var formGroup = field.parentElement;
    var errorSpan = document.createElement("span");
    errorSpan.className = "error-message";
    errorSpan.style.color = "red";
    errorSpan.style.fontSize = "12px";
    errorSpan.textContent = message;
    formGroup.appendChild(errorSpan);
  }

  // ---------------------- 添加中间件功能 ----------------------
  var addMiddlewareModal = document.getElementById("addMiddlewareModal");
  var addMiddlewareBtn = document.getElementById("addMiddlewareBtn");
  var addMiddlewareClose = document.getElementById("addMiddlewareClose");
  var middlewareCancelBtn = document.getElementById("middlewareCancelBtn");
  var addMiddlewareForm = document.getElementById("addMiddlewareForm");

  if (addMiddlewareBtn) {
    addMiddlewareBtn.onclick = function() { addMiddlewareModal.style.display = "block"; };
  }
  if (addMiddlewareClose) {
    addMiddlewareClose.onclick = function() { addMiddlewareModal.style.display = "none"; };
  }
  if (middlewareCancelBtn) {
    middlewareCancelBtn.onclick = function() { addMiddlewareModal.style.display = "none"; };
  }
  window.onclick = function(event) {
    if (event.target === addMiddlewareModal) { addMiddlewareModal.style.display = "none"; }
  };

  addMiddlewareForm.onsubmit = function(e) {
    e.preventDefault();
    clearErrors(addMiddlewareForm);
    var formData = new FormData(addMiddlewareForm);
    var valid = true;
    // 检查是否至少填写一项
    var hasSome = false;
    for (var i = 0; i < propertiesData.length; i++) {
      var prop = propertiesData[i];
      var field = addMiddlewareForm.elements[prop.name];
      if (field && field.value.trim() !== "") { hasSome = true; break; }
    }
    if (!hasSome) {
      if (propertiesData.length > 0) {
        var firstField = addMiddlewareForm.elements[ propertiesData[0].name ];
        if (firstField) { showError(firstField, "输入不能为空，至少填写一项信息"); }
      } else { alert("输入不能为空，至少填写一项信息"); }
      return false;
    }
    // 检查必填项（如果 middleware_properties 中标记为 required 则不能为空）
    for (var i = 0; i < propertiesData.length; i++) {
      var prop = propertiesData[i];
      var field = addMiddlewareForm.elements[prop.name];
      if (prop.required && field && !field.value.trim()) {
        showError(field, "字段 " + prop.name + " 为必填项");
        valid = false;
      }
    }
    // 对非空字段根据属性类型验证格式
    for (var i = 0; i < propertiesData.length; i++) {
      var prop = propertiesData[i];
      var field = addMiddlewareForm.elements[prop.name];
      if (field && field.value.trim() !== "") {
        var val = field.value.trim();
        if (prop.type === "IP") {
          var regexIP = /^((25[0-5]|2[0-4]\d|1?\d?\d)(\.|$)){4}$/;
          if (!regexIP.test(val)) { showError(field, "必须为有效的IP地址格式，如 255.255.255.255"); valid = false; }
        }
        if (prop.type === "数字") {
          if (isNaN(val)) { showError(field, "必须为数字"); valid = false; }
        }
        if (prop.type === "MAC") {
          var regexMAC = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
          if (!regexMAC.test(val)) { showError(field, "必须为有效的MAC地址格式，如 AA:BB:CC:DD:EE:FF"); valid = false; }
        }
        if (prop.type === "日期") {
          var regexDate = /^\d{4}-\d{2}-\d{2}$/;
          if (!regexDate.test(val)) { showError(field, "必须为有效的日期格式，如 2023-01-01"); valid = false; }
          else { var d = new Date(val); if (isNaN(d.getTime())) { showError(field, "无效的日期"); valid = false; } }
        }
        if (prop.type === "时间") {
          var regexTime = /^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/;
          if (!regexTime.test(val)) { showError(field, "必须为有效的时间格式，如 14:30:00"); valid = false; }
        }
        if (prop.type === "邮箱") {
          var regexEmail = /^\S+@\S+\.\S+$/;
          if (!regexEmail.test(val)) { showError(field, "必须为有效的邮箱格式"); valid = false; }
        }
        if (prop.type === "布尔") {
          var regexBoolean = /^(true|false)$/i;
          if (!regexBoolean.test(val)) { showError(field, "必须为布尔值：true 或 false"); valid = false; }
        }
      }
    }
    if (!valid) return false;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", addMiddlewareForm.getAttribute("action"), true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        var res = JSON.parse(xhr.responseText);
        if (res.success) { location.reload(); }
        else { alert(res.message); }
      }
    };
    xhr.send(formData);
  };

  // ---------------------- 编辑中间件功能 ----------------------
  var editMiddlewareModal = document.getElementById("editMiddlewareModal");
  var editMiddlewareClose = document.getElementById("editMiddlewareClose");
  var editMiddlewareCancelBtn = document.getElementById("editMiddlewareCancelBtn");
  var editMiddlewareForm = document.getElementById("editMiddlewareForm");
  var currentEditMiddlewareId = null;
  document.querySelectorAll('.editBtn').forEach(function(button) {
    button.addEventListener('click', function() {
      var row = this.closest('tr');
      currentEditMiddlewareId = row.getAttribute('data-id');
      var recordJson = row.getAttribute('data-record');
      var record = {};
      if (recordJson) { record = JSON.parse(recordJson); }
      var inputs = editMiddlewareForm.querySelectorAll('input[type="text"]');
      inputs.forEach(function(input) {
        var fieldName = input.getAttribute('name');
        input.value = record[fieldName] || '';
      });
      editMiddlewareModal.style.display = "block";
    });
  });
  if (editMiddlewareClose) {
    editMiddlewareClose.onclick = function() { editMiddlewareModal.style.display = "none"; };
  }
  if (editMiddlewareCancelBtn) {
    editMiddlewareCancelBtn.onclick = function() { editMiddlewareModal.style.display = "none"; };
  }
  window.onclick = function(event) {
    if (event.target === editMiddlewareModal) { editMiddlewareModal.style.display = "none"; }
  };
  editMiddlewareForm.onsubmit = function(e) {
    e.preventDefault();
    clearErrors(editMiddlewareForm);
    var formData = new FormData(editMiddlewareForm);
    var valid = true;
    for (var i = 0; i < propertiesData.length; i++) {
      var prop = propertiesData[i];
      var field = editMiddlewareForm.elements[prop.name];
      if (prop.required && field && !field.value.trim()) {
        showError(field, "字段 " + prop.name + " 为必填项");
        valid = false;
      }
      if (field && field.value.trim() !== "") {
        var val = field.value.trim();
        if (prop.type === "IP") {
          var regexIP = /^((25[0-5]|2[0-4]\d|1?\d?\d)(\.|$)){4}$/;
          if (!regexIP.test(val)) { showError(field, "必须为有效的IP地址格式，如 255.255.255.255"); valid = false; }
        }
        if (prop.type === "数字") {
          if (isNaN(val)) { showError(field, "必须为数字"); valid = false; }
        }
        if (prop.type === "MAC") {
          var regexMAC = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
          if (!regexMAC.test(val)) { showError(field, "必须为有效的MAC地址格式，如 AA:BB:CC:DD:EE:FF"); valid = false; }
        }
        if (prop.type === "日期") {
          var regexDate = /^\d{4}-\d{2}-\d{2}$/;
          if (!regexDate.test(val)) { showError(field, "必须为有效的日期格式，如 2023-01-01"); valid = false; }
          else { var d = new Date(val); if (isNaN(d.getTime())) { showError(field, "无效的日期"); valid = false; } }
        }
        if (prop.type === "时间") {
          var regexTime = /^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/;
          if (!regexTime.test(val)) { showError(field, "必须为有效的时间格式，如 14:30:00"); valid = false; }
        }
        if (prop.type === "邮箱") {
          var regexEmail = /^\S+@\S+\.\S+$/;
          if (!regexEmail.test(val)) { showError(field, "必须为有效的邮箱格式"); valid = false; }
        }
        if (prop.type === "布尔") {
          var regexBoolean = /^(true|false)$/i;
          if (!regexBoolean.test(val)) { showError(field, "必须为布尔值：true 或 false"); valid = false; }
        }
      }
    }
    if (!valid) return false;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "{{ url_for('update_middleware', middleware_id=0) }}".replace("0", currentEditMiddlewareId), true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        var res = JSON.parse(xhr.responseText);
        if (res.success) { editMiddlewareModal.style.display = "none"; location.reload(); }
        else { alert("修改失败：" + res.message); }
      }
    };
    xhr.send(formData);
  };

  // ---------------------- 删除中间件功能 ----------------------
  document.querySelectorAll('.deleteBtn').forEach(function(button) {
    button.addEventListener('click', function() {
      var middlewareId = this.getAttribute("data-id");
      if (confirm("确定要删除该中间件吗？")) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "{{ url_for('delete_middleware_single', middleware_id=0) }}".replace("0", middlewareId), true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4 && xhr.status === 200) { location.reload(); }
        };
        xhr.send();
      }
    });
  });
  document.getElementById("batchDeleteBtn").onclick = function() {
    var selected = [];
    document.querySelectorAll("input[name='selected_ids']:checked").forEach(function(item) {
      selected.push(item.value);
    });
    if (selected.length === 0) {
      alert("请先选择要删除的中间件记录");
      return;
    }
    if (confirm("确定要批量删除所选记录吗？")) {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "{{ url_for('delete_middleware_batch') }}", true);
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) { location.reload(); }
      };
      xhr.send("ids=" + selected.join(','));
    }
  };

  // ---------------------- 可选列功能 ----------------------
  var chooseColsBtn = document.getElementById("chooseColsBtn");
  var columnModal = document.getElementById("columnModal");
  var columnClose = document.getElementById("columnClose");
  var columnCancelBtn = document.getElementById("columnCancelBtn");
  var columnForm = document.getElementById("columnForm");

  chooseColsBtn.onclick = function() { columnModal.style.display = "block"; };
  columnClose.onclick = function() { columnModal.style.display = "none"; };
  columnCancelBtn.onclick = function() { columnModal.style.display = "none"; };
  window.onclick = function(event) {
    if (event.target === columnModal) { columnModal.style.display = "none"; }
  };
  columnForm.onsubmit = function(e) {
    e.preventDefault();
    var checkboxes = columnForm.querySelectorAll('input[type="checkbox"][name="columns"]');
    checkboxes.forEach(function(checkbox) {
      var colClass = "col-" + checkbox.value;
      var headerCells = document.querySelectorAll("th." + colClass);
      var cells = document.querySelectorAll("td." + colClass);
      if (checkbox.checked) {
        headerCells.forEach(function(cell) { cell.style.display = ""; });
        cells.forEach(function(cell) { cell.style.display = ""; });
      } else {
        headerCells.forEach(function(cell) { cell.style.display = "none"; });
        cells.forEach(function(cell) { cell.style.display = "none"; });
      }
    });
    columnModal.style.display = "none";
  };

  // ---------------------- 密码字段切换功能 ----------------------
  // 针对中间件管理中属性类型为"password"的字段，添加小眼睛图标切换效果
  document.querySelectorAll('.toggle-password').forEach(function(icon) {
    icon.addEventListener('click', function() {
      var parent = this.parentElement;
      var hiddenSpan = parent.querySelector('.password-hidden');
      var realSpan = parent.querySelector('.password-real');
      if (hiddenSpan.style.display !== 'none') {
        hiddenSpan.style.display = 'none';
        realSpan.style.display = 'inline';
        this.classList.remove('fa-eye');
        this.classList.add('fa-eye-slash');
      } else {
        hiddenSpan.style.display = 'inline';
        realSpan.style.display = 'none';
        this.classList.remove('fa-eye-slash');
        this.classList.add('fa-eye');
      }
    });
  });
});
</script>
{% endblock %}
